import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

path = './data.txt'
data = pd.read_csv(path, header=None)
plt.scatter(data[:][0], data[:][1], marker='.')

# data = np.array(data)
m = data.shape[0]
x = data[[0]]
y = data[1]  #  ------------------yy
# print("x:\n",x)
# print("y:\n",y)
x = np.array(x)


def gradient(theat,x,y):

    grad = np.empty(len(theat))
    grad[0] = np.sum(x.dot(theat)-y)

    for i in range(1,len(grad)):
        grad[i] = (x.dot(theat) - y).dot(x[:,i])

    return grad


def cost_function(x, theta, y):
    print(x.shape)
    cost = np.sum((x.dot(theta) - y) ** 2)
    print("cost",cost)
    return cost / (2 * 97)



def gradient_descent(x,  y, eat):
    x = np.hstack([np.ones([m, 1]), x])
    y = np.array(y)
    theta = np.zeros([x.shape[1]])


    while True:
        last_theta = theta
        print(last_theta)
        grad = gradient(theta, x, y)
        theta = theta - grad * eat
        print(theta)
        # if abs(cost_function(x, last_theta, y)-cost_function(x, theta, y)) < 1e-15:
        #     break
        if abs(cost_function(x, last_theta, y) - cost_function(x, theta, y)) < 1e-15:

            break

    return theta






res = gradient_descent(x, y, 0.0001)


X = np.arange(3, 25)

Y = res[0] + res[1] * X

plt.plot(X, Y, color='r')
plt.show()